`timescale 1ns/1ps
`default_nettype none

module tinybus_gpio_slave #(
    parameter REG_NUM = 4
)(
    input  wire        clk,
    input  wire        rstn,
    // TinyBus 从机接口（与 tinybus_dmem_slave 一致命名）
    input  wire        req_valid,
    input  wire [31:0] req_addr,
    input  wire [31:0] req_wdata,
    input  wire [3:0]  req_be,
    input  wire        req_we,
    output wire        req_ready,
    output wire        rsp_valid,
    output wire [31:0] rsp_rdata,
    output wire        rsp_err,

    output wire [7:0]  gpio_out
);
    // 零等待
    assign req_ready = 1'b1;
    assign rsp_valid = req_valid;
    assign rsp_err   = 1'b0;

    // 4×32 位寄存器，地址低两位选寄存器
    reg [31:0] regs [0:REG_NUM-1];
    wire [1:0] ridx = req_addr[3:2];

    integer i;
    always @(posedge clk) begin
        if (!rstn) begin
            for (i=0;i<REG_NUM;i=i+1) regs[i] <= 32'h0;
        end else if (req_valid && req_we) begin
            if (req_be[0]) regs[ridx][ 7: 0] <= req_wdata[ 7: 0];
            if (req_be[1]) regs[ridx][15: 8] <= req_wdata[15: 8];
            if (req_be[2]) regs[ridx][23:16] <= req_wdata[23:16];
            if (req_be[3]) regs[ridx][31:24] <= req_wdata[31:24];
        end
    end

    assign rsp_rdata = regs[ridx];
    assign gpio_out  = regs[0][7:0];

endmodule
`default_nettype wire
